import { errResponse, getTimeStr, checkRequire } from '../../utils/utils';
import { VoteUser } from '../../entity/voteuser.entity';
import { getManager, Repository } from 'typeorm';

/**
 * @apiDefine myInfoCtrl
 * @apiParam {String} test 用户名1111.
 */
export class RegisterCtrl {
  public static async index(ctx: any) {
    const params = ctx.request.body;
    const require = ['username', 'password'];
    const userRepository: Repository<VoteUser> = getManager().getRepository(
      VoteUser
    );
    const userData: VoteUser = new VoteUser();
    // 判断参数是否缺少
    const isRequire = checkRequire(require, params);
    if (isRequire !== true) {
      errResponse(ctx, 400, `缺少参数${isRequire}`);
      return;
    }
    let type: string = params.type ? params.type : 'USER';
    let createTime: number = getTimeStr();
    userData.u_name = params.username;
    userData.u_password = params.password;
    userData.u_type = type;
    userData.u_createtime = createTime;
    userData.u_status = 'NORMAL';
    // 判断用户名是否重复
    const usernameIfUnique = await userRepository.findOne({
      u_name: userData.u_name
    });
    if (usernameIfUnique) {
      errResponse(ctx, 400, '用户名已存在！');
      return;
    }
    await userRepository.save(userData);
    ctx.status = 200;
    // ctx.body = { success: true }
  }
}
